<template>
  <a-modal :open="open" width="640px" :title="title" centered :ok-button-props="{ disabled: !isCompleted }" ok-text="保存" @ok="onOk" @cancel="onCancel">
    <a-form class="form-style-flex" name="validate_other" :model="formState">
      <a-form-item v-if="title == '修改出库单'" label="出库单号" class="w-full">
        <a-input v-model:value="formState.ckdh" disabled placeholder="入库单号" />
      </a-form-item>
      <a-form-item label="出库仓库" class="w-1/2" v-bind="validateInfos.ckmc">
        <SelectWarehouse v-model:value="formState.ckmc" @select="onSelectWarehouse" />
      </a-form-item>
      <a-form-item label="制单人" class="w-1/2">
        {{ formState.jbrmc }}
      </a-form-item>
      <a-form-item label="去向" class="w-full" v-bind="validateInfos.qx">
        <a-input v-model:value="formState.qx" placeholder="去向" />
      </a-form-item>
      <a-form-item label="备注" class="w-full">
        <a-textarea v-model:value="formState.remarks" :rows="5" placeholder="请输入" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { post } from '@/utils/request'
import SelectWarehouse from '@/components/SelectWarehouse'
import useUserStore from '@/store/user'

const { empId, empName } = useUserStore()

const router = useRouter()
const emit = defineEmits(['update:open', 'update:value', 'success'])
const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => ({})
  },
  title: {
    type: String,
    default: ''
  }
})

const formState = ref({
  fpzt: '0',
  jbrmc: empName,
  jbr: empId,
  ckmc: '',
  qx: ''
})
const rulesState = ref({
  ckmc: [{ required: true, message: '请选择出库仓库' }],
  qx: [{ required: true, message: '请输入去向' }]
})
const { isCompleted, resetFields, validate, validateInfos } = useForm(formState, rulesState)
watch(
  () => props.open,
  (val) => {
    if (val) {
      if (props.rowData?.rkdh !== '') {
        formState.value = {
          jbrmc: empName,
          jbr: empId,
          ...props.rowData
        }
      }
    }
  }
)

const onOk = async () => {
  await validate()
  const formData = {
    ckdh: formState.value.ckdh || '',
    ...formState.value
  }
  const res = await post('/materials/psiform/doSaveOutBoundHead', formData)
  if (res.code === 0) {
    message.success(res.msg)
    if (!props.rowData?.ckdh) {
      router.push({
        path: '/material/warehouse/out-store-detail',
        query: {
          ckdh: res.data.ckdh
        }
      })
    }

    emit('update:open', false)

    emit('success')
  } else {
    message.error(res.msg)
  }
}

const onCancel = () => {
  emit('update:open', false)
  resetFields()
}

const onSelectWarehouse = (_, supplier) => {
  formState.value.ckbh = supplier?.ckid
  formState.value.ckmc = supplier?.ckmc
}
</script>
<style lang="less" scoped></style>
